<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>工序(PU)详情</title>
    <!-- 引入 Element UI 的样式 -->
    <link rel="stylesheet" href="../../assets/css/element-ui.css" />
    <link rel="stylesheet" href="../../assets/css/styles.css" />
    <script src="../../assets/js/cdn.js"></script>
    <link rel="stylesheet" href="../../assets/fontawesome-free-6.7.2-web/css/all.min.css" />
  </head>
  <body>
    <div id="app">
      <lx-header slot="header" v-on:toggle="isToggle = !isToggle" :type="2"></lx-header>
      <div class="main-content">
        <div class="content" style="width: 100%">

          <h1 class="module-title">基本信息</h1>
          <div class="center-grid mb-20">
            <el-descriptions :column="4">
              <el-descriptions-item v-for="item in baseInfoHeader" :key="item.fieldApi" :label="item.label">
                <div>{{ formInfo[item.fieldApi] ? formInfo[item.fieldApi]:'-' }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <h1 class="module-title">作业指导书</h1>
          <!-- 添加图片预览区域 -->
          <div v-if="formInfo.puFile" class="image-preview-container">
            <el-image
                    :src="formInfo.puFile"
                    :preview-src-list="[formInfo.puFile]"
                    fit="contain"
                    class="preview-image">
            </el-image>
          </div>
        </div>
      </div>

    </div>
    <script src="../../assets/js/constant.js"></script>
    <script src="../../assets/js/utils.js"></script>
    <script src="../../assets/js/auth.js"></script>
    <script src="../../assets/js/axios.min.js"></script>
    <!-- 引入 Vue.js -->
    <script src="../../assets/js/vue.js"></script>
    <!-- 引入 Element UI 的 JS 文件 -->
    <script src="../../assets/js/element-ui.js"></script>

    <script type="module">
      import LxHeader from '../../pages/components/LxHeader/index.js'
      Vue.component('lx-header', LxHeader)
      checkAuthentication(2)
      new Vue({
        el: '#app',
        components: {},
        data() {
         return {
            currentUser: JSON.parse(localStorage.getItem('currentUser')) || {},
            userMenuList: JSON.parse(localStorage.getItem('userMenuList')) || [],
            businessCenters: [
                { name: '订单中心', path: '../index.html' },
                { name: '用户中心', path: '#' },
                { name: '产品中心', path: '#' },
                { name: '库存中心', path: '#' },
                { name: '财务中心', path: '#' },
                { name: '数据中心', path: '#' },
                { name: '系统中心', path: '#' },
                { name: '消息中心', path: '#' }
            ],
            baseInfoHeader: [
              { label: '工序编号', fieldApi: 'puCode' },
              { label: '工序名称', fieldApi: 'puName'},
              { label: '归属部门', fieldApi: 'departmentCode'},
            ],
            imageUrl:'',
            dicts: ['base_component_unit','base_tools_type','base_accessories_type','component_attribute'],
            optionsObj: [],
            // 选中数组
            codes: [],
            formInfo: {},
            detailDialog: false, // 详情
            puCode: '',
            root_host: root_host,
            request_host: request_host,
            openComponentDia: false,
            openToolDia: false,
            queryParams: {
              pageNo: 1,
              pageSize: 10,
              puCode: '',
              puName: ''
            },
            // 上传相关
            fileList: [],
            headers: {}
          }
        },
        created() {
          this.init()
        },
        methods: {
          exit,
          init() {
            this.puCode = getUrlParameter('puCode')
            this.getOptions()
            this.getDetails()
            this.getComponentList()
            this.getToolList()
            this.getAccessoriesList()
          },
          beforeUpload(file) {
            const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
            if (!isJPGOrPNG) {
              this.$message.error('只允许上传图片格式');
              return false;
            }
            this.imageUrl = URL.createObjectURL(file);
            return true;
          },
          getDetails() {
            // 这里替换为实际的API调用
            axios.get(`${this.request_host}/system/pu/` + this.puCode)
                .then(response => {
                    this.formInfo = response.data.data
                });
          },
          getOptions() {
                this.dicts.forEach((item) => {
                    axios.get(`${this.request_host}/system/dict/data/type/${item}`).then((response) => {
                        this.$set(this.optionsObj, item, {})
                        if (response.status == 200) {
                            response.data.data.map((item1) => {
                                this.optionsObj[item][item1.dictValue] = item1.dictLabel
                            })
                        }
                    })
                })
          },
          getOptionsStr(opt, value) {
              if (this.optionsObj[opt] && value) {
                  return this.optionsObj[opt][value]
              }
              return ''
          },
          getComponentList() {
            const componentParamesInput = {
              puCode: this.puCode,
              componentAttribute: '1' //输入
            }
            axios.post(`${this.request_host}/system/pu/queryComponentsByPuId`,componentParamesInput).then((response) => {
                if (response.status == 200) {
                  this.componentTableDataInput = response.data.rows
                }
              });
            const componentParamesOutput = {
              puCode: this.puCode,
              componentAttribute: '2' //输出
            }
            axios.post(`${this.request_host}/system/pu/queryComponentsByPuId`,componentParamesOutput).then((response) => {
                if (response.status == 200) {
                  this.componentTableDataOutput = response.data.rows
                }
              })
          },
          getToolList() {
            axios.get(`${this.request_host}/system/pu/queryToolsByPuId?puCode=`+this.puCode).then((response) => {
                if (response.status == 200) {
                  this.toolTableData = response.data.rows
                }
              })
          },
          getAccessoriesList() {
            axios.get(`${this.request_host}/system/pu/queryAccessoriesByPuId?puCode=`+this.puCode).then((response) => {
                if (response.status == 200) {
                  this.AccessoriesTableData = response.data.rows
                }
              })
          },
          addComponent(val){
            this.openComponentDia = true
            axios.get(`${this.request_host}/system/component/list`,{ params: this.queryParams }).then((response) => {
                if (response.status == 200) {
                  this.chooseComponentTable = response.data.rows
                  this.chooseComponentTotal = response.data.total
                }
              });
              this.addComponentFlag = val
          },
          // 多选框选中数据
          selectionComponentChange(selection) {
              this.codes = selection.map(item => item.componentCode)
          },
          // 添加关联部件数据
          addComponentData(){
            const addComponentParams = {
              puCode: this.puCode,
              codes: this.codes,
              type: 0,
              componentAttribute: this.addComponentFlag
            }
            axios.post(`${this.request_host}/system/pu/addPuRelationData`,addComponentParams).then((response) => {
                if (response.status == 200) {
                  this.getComponentList()
                  this.cancleAdd()
                }
              })
          },
          cancleAdd(){
            this.codes = []
            this.openComponentDia = false
            this.openToolDia = false
            this.openAccessoriesDia = false
          },
          // 多选框选中数据
          selectionToolChange(selection) {
              this.codes = selection.map(item => item.toolCode)
          },
          addTool(){
            this.openToolDia = true
            axios.get(`${this.request_host}/system/tools/list`,{ params: this.queryParams }).then((response) => {
                if (response.status == 200) {
                  this.chooseToolTable = response.data.rows
                  this.chooseToolTotal = response.data.total
                }
              })
          },
          // 添加关联工具数据
          addToolData(){
            const addToolParams = {
              puCode: this.puCode,
              codes: this.codes,
              type: 1
            }
            axios.post(`${this.request_host}/system/pu/addPuRelationData`,addToolParams).then((response) => {
                if (response.data.code == 200) {
                  this.getToolList()
                  this.cancleAdd()
                }else{
                  this.$message.error(response.data.msg);
                }
              })
          },
          addAccessories(){
            this.openAccessoriesDia = true
            axios.get(`${this.request_host}/system/accessories/list`,{ params: this.queryParams }).then((response) => {
                if (response.status == 200) {
                  this.chooseAccessoriesTable = response.data.rows
                  this.chooseAccessoriesTotal = response.data.total
                }
              })
          },
          selectionAccessoriesChange(selection){
            this.codes = selection.map(item => item.accessoriesCode)
          },
          addAccessoriesData(){
            const addAccessoriesParams = {
              puCode: this.puCode,
              codes: this.codes,
              type: 2
            }
            axios.post(`${this.request_host}/system/pu/addPuRelationData`,addAccessoriesParams).then((response) => {
                if (response.data.code == 200) {
                  this.getAccessoriesList()
                  this.cancleAdd()
                }else{
                  this.$message.error(response.data.msg);
                }
              })
          },
          handleUpdate(url){
            // 修改跳转到对应列表页
            window.open(url)
          },
          // 删除pu关联数据
          delData(row,type){
            const delParams = {
              type: type,
              puCode: this.puCode,
              delId: ''
            }
            // 数据删除
            if (type === 0) {
              //部件
              delParams.delId = row.id
            }
            if (type === 1) {
              // 工具工装
              delParams.delId = row.toolCode
            }
            if (type === 2) {
              // 辅料
              delParams.delId = row.accessoriesCode
            }
            axios.post(`${this.request_host}/system/pu/delPuRelationData`,delParams).then((response) => {
                if (response.status == 200) {
                  this.init()
                }
              })
          },
          // 上传成功回调
          handleUploadSuccess(response, file, fileList) {
            if (response.code === 200) {
              this.$message.success('上传成功');
              this.formInfo.puFile = response.data;
              // 更新文件列表，只显示文件名
              this.fileList = [{
                name: file.name,
                url: response.data
              }];
            } else {
              this.$message.error(response.msg || '上传失败');
            }
          },
          // 处理文件下载
          handleDownload(file) {
            if (file.url) {
              window.open(this.request_host + '/system/pu/download?filePath=' + encodeURIComponent(file.url));
            }
          },
          // 处理文件删除
          handleDeleteFile(file) {
            this.$confirm('确认删除该文件吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              axios.post(`${this.request_host}/system/pu/deleteFile`, {
                puCode: this.puCode,
                filePath: file.url
              }).then(response => {
                if (response.status == 200) {
                  this.$message.success('删除成功');
                  this.fileList = [];
                  this.formInfo.puFile = '';
                }
              }).catch(error => {
                console.error('删除失败:', error);
                this.$message.error('删除失败');
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });
          },
          // 上传失败回调
          handleUploadError(err) {
            this.$message.error('上传失败');
            console.error('上传失败:', err);
          },
          // 处理工具数量变更
          handleToolNumChange(row) {
            axios.post(`${this.request_host}/system/pu/updateToolNum`, {
              puCode: this.puCode,
              toolCode: row.toolCode,
              toolNum: row.toolNum
            }).then(response => {
              if (response.status == 200) {
                this.$message.success('保存成功');
              }
            }).catch(error => {
              console.error('保存失败:', error);
              this.$message.error('保存失败');
            });
          },
          // 处理工具数量变更
          handleAccessoriesNumChange(row) {
            axios.post(`${this.request_host}/system/pu/updateAccessoriesNum`, {
              puCode: this.puCode,
              accessoriesCode: row.accessoriesCode,
              accessoriesNum: row.accessoriesNum
            }).then(response => {
              if (response.status == 200) {
                this.$message.success('保存成功');
              }
            }).catch(error => {
              console.error('保存失败:', error);
              this.$message.error('保存失败');
            });
          },
          openMenu(url) {
            window.open(url)
          },
        }
      })
    </script>
    <style>
      .el-table th.el-table__cell {
        background-color: #f2f2f2; /* 例如，设置为浅灰色 */
      }
      .mb8 {
            height: 30px;
        }
    </style>
  </body>
</html>
